home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1364 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.8 KB  |  68 lines

  1. Newsgroups: comp.lang.c++
  2. Path: uu4news.netcom.com!friend!news
  3. From: rich@kastle.com (Richard Krehbiel)
  4. Subject: Re: Syntax for looping through enumerated types
  5. Message-ID: <1996Jan10.163922.7855@friend.kastle.com>
  6. Sender: news@friend.kastle.com (News)
  7. Reply-To: rich@kastle.com
  8. Organization: Kastle Development Associates
  9. X-Newsreader: Forte Free Agent 1.0.82
  10. References: <4cs70o$8ns@ornews.intel.com>
  11. Date: Wed, 10 Jan 1996 16:41:18 GMT
  12.  
  13. thurman_b_miller@ccm2.hf.intel.com (Thurman Miller) wrote:
  14.  
  15. >Suppose I have:
  16.  
  17. >enum daysoftheweek {MONDAY, TUESDAY, WEDNESDAY,THURSDAY,FRIDAY} ;
  18.  
  19. >How can I loop through this using a for statement?
  20.  
  21. >(the following doesn't work)
  22.  
  23. >daysoftheweek nIndex;
  24. >for (nIndex=MONDAY;nIndex<=FRIDAY;nIndex++)
  25. >{
  26.  
  27. >    switch (nIndex):
  28. >    {
  29. >        case  MONDAY:
  30. >            doMonday();
  31. >    }
  32.  
  33. >}
  34.  
  35. >I'd like to get away from specifying the beginning & end (ie MONDAY &
  36. >TUESDAY) if possible because my enumerated list will constanty grow
  37. >and I'd like to only change the definition of the enumerated list and
  38. >the for statement would continue to work.
  39.  
  40. >Note: This is just a trivial example, not what I'm actually wanting to
  41. >do.
  42.  
  43. Enum values don't have any built-in constraint that says they'll have
  44. consecutive unique values.  You have to ensure this yourself (but it's
  45. easy).
  46.  
  47. To iterate through enums that I maintain, I add special "first value"
  48. and "last value" tags:
  49.  
  50. enum daysoftheweek {
  51.     FIRST__DAY, MONDAY=FIRST_DAY, TUESDAY, WEDNESDAY, THURSDAY,
  52.     FRIDAY, SATURDAY, SUNDAY, END__DAY };
  53.  
  54. daysoftheweek nIndex;
  55.  
  56. for(nIndex = FIRST__DAY; nIndex < END__DAY; nIndex++)
  57. {
  58.    // etc
  59. }
  60.  
  61. You have to keep FIRST__DAY and END__DAY correct, and you can add
  62. enums between to your heart's content.
  63.  
  64. --
  65. Richard Krehbiel, Kastle Systems, Arlington VA USA
  66. rich@kastle.com (work) or richk@cais.com (personal)
  67.  
  68.